package top.lingkang.mm.page;

import cn.hutool.core.lang.Assert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import top.lingkang.mm.error.MagicException;
import top.lingkang.mm.transaction.TransactionManage;
import top.lingkang.mm.utils.MagicUtils;

import java.sql.Connection;

/**
 * @author lingkang
 * Created by 2024/3/3
 */
public class PageHelper {
    private static final Logger log = LoggerFactory.getLogger(PageHelper.class);
    private static final ThreadLocal<PageInfo> local = new ThreadLocal<>();
    /**
     * 分页处理，您可以手动修改实现, 更多请查看：{@link PageSqlHandle}
     */
    public static PageSqlHandle pageSqlHandle;

    /**
     * 开始分页
     *
     * @param page 默认 1
     * @param size 默认 10
     */
    public static void startPage(int page, int size) {
        Assert.isTrue(page > 0, "page 最小值为 1");
        Assert.isTrue(size > 0, "size 必须大于 0");
        PageInfo info = new PageInfo();
        info.setSize(size);
        info.setPage(page);
        info.setComplete(false);
        local.set(info);
    }

    /**
     * 分页查询完成时，调用一次后移除
     */
    public static PageInfo getPage() {
        PageInfo info = local.get();
        if (info == null)
            return null;
        if (info.isComplete())
            local.remove();
        return info;
    }

    public static void initPageHandler(Connection connection) {
        getHandle(connection);
    }

    public static PageSqlHandle getHandle(Connection connection) {
        if (pageSqlHandle != null) {
            return pageSqlHandle;
        }
        try {
            String url = MagicUtils.getDatabaseURL(connection, false);
            pageSqlHandle = getByType(url);
            if (pageSqlHandle == null)
                throw new MagicException("未识别的数据库类型：" + url);
        } catch (Exception e) {
            log.warn("分页识别数据库类型失败，将默认使用mysql处理，您可以更改 PageHelper.pageSqlHandle 分页处理", e);
            pageSqlHandle = new PageSqlHandleMySql();
        }
        return pageSqlHandle;
    }

    private static PageSqlHandle getByType(String name) {
        name = name.toLowerCase();
        if (name.contains(":mysql:")) {
            return new PageSqlHandleMySql();
        } else if (name.contains(":postgresql:")) {
            return new PageSqlHandlePostgreSql();
        } else if (name.contains(":h2:")) {
            return new PageSqlHandleH2();
        } else if (name.contains(":sqlite:")) {
            return new PageSqlHandleSqlite();
        } else if (name.contains(":sqlserver:")) {
            return new PageSqlHandleSqlServer();
        }
        return null;
    }
}
